package com.sdhs.common.config;

import com.sdhs.common.utils.mqtt.MqttProperties;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * FileName: MqttOutboundConfiguration
 * Description: TODO
 * @author sdmq
 */
@Slf4j
@Configuration
public class MqttOutboundConfiguration {

	@Autowired
	private MqttProperties mqttProperties;

	@Bean
	@ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true", matchIfMissing = false)
	public MqttConnectOptions getMqttConnectOptions() {
		MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
		// 超级用户 , 否则使用clinetId配置
		mqttConnectOptions.setUserName(mqttProperties.getUsername());
		mqttConnectOptions.setPassword(mqttProperties.getPassword().toCharArray());
		mqttConnectOptions.setServerURIs(new String[]{mqttProperties.getHostUrl()});
		// 设置超时时间 默认30
		mqttConnectOptions.setConnectionTimeout(60);
		// 设置会话心跳时间 60
		mqttConnectOptions.setKeepAliveInterval(60);
		return mqttConnectOptions;
	}

	@Bean
	@ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true", matchIfMissing = false)
	public MqttPahoClientFactory mqttClientFactory() {
		DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
		factory.setConnectionOptions(getMqttConnectOptions());
		return factory;
	}

	@Bean
	@ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true", matchIfMissing = false)
	@ServiceActivator(inputChannel = "mqttOutboundChannel")
	public MessageHandler mqttOutbound() {
		MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(mqttProperties.getClientId() + "p",
				mqttClientFactory());
		messageHandler.setAsync(true);
		messageHandler.setDefaultTopic(mqttProperties.getDefaultTopic());
		return messageHandler;
	}

	@Bean
	//@ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true", matchIfMissing = false)
	public MessageChannel mqttOutboundChannel() {

		return new DirectChannel();
	}

}
